import config from '../utils/config'
import utils from '../utils/utils'


const post = (title, url, data, back) => {
  !title ? null : utils.loading(title)
  const configUrl = config.config.url;
  wx.request({
    url: configUrl + url,
    data: data,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
    success: function (res) {
      if (res.data.status == 200) {
        back(res.data);
      } else {
        utils.toast('error', res.data.msg)
      }
      wx.hideLoading();
    },
    fail: function (res) {
      utils.toast('error', '请求失败')
    },
  })
}

const get = (title, url, data, back) => {
  utils.loading(title)
  let params = '';
  Object.keys(data).forEach((key) => {
    params += params ? '&' : '?'
    params += `${key}=${data[key]}`
  })
  const configUrl = config.config.url;
  console.log(`${configUrl}${url}${params}`);
  wx.request({
    url: `${configUrl}${url}${params}`,
    header: {
      'content-type': 'application/json',
    },
    method: 'GET',
    success: function (res) {
      wx.hideLoading();
      if (res.data.status == 200) {
        back(res.data);
      } else {
        utils.toast('error', res.data.msg)
      }
    },
    fail: function (res) {
      utils.toast('error', '请求失败')
      back(res)
    },
  })
}

const _uploadFile = (title, url, file, data, back) => {
  utils.loading(title)
  const configUrl = config.config.url;
  file.forEach((e, i) => {
    let index = i;
    wx.uploadFile({
      url: configUrl + url,
      filePath: e,
      name: 'file',
      formData: data,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        "accept": "application/json"
      },
      success: function (res) {
        let data = JSON.parse(res.data)
        if (data.status !== 200) {
          utils.toast('error', "上传失败")
          return
        }
        if (index + 1 === file.length) {
          // utils.toast('success', "上传成功")
          back(true)
        }
      },
      fail: function (res) {
        utils.toast('error', '请求失败')
      },
    })
  });

}

module.exports = {
  post,
  get,
  _uploadFile
}